﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using ERP_SaaS_WinForm.登录.Common;
using Newtonsoft.Json;

namespace ERP_SaaS_WinForm
{
    public partial class LoginForm : CCSkinMain
    {
        public LoginForm()
        {
            InitializeComponent();
            this.txtUserName.Focus();//聚焦用户名输入框
        }
        private void ShowAlert(string message,string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK, caption == "成功" ? MessageBoxIcon.Information 
                : caption == "提示" ? MessageBoxIcon.Information 
                : MessageBoxIcon.Error);
        }

        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            string userName=txtUserName.Text.Trim();
            string pwd=txtPwd.Text.Trim();

            if(string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd))
            {
                ShowAlert("请输入用户名和密码", "提示");
                return;
            }
            try
            {
                var body = new { userName = userName, pwd = pwd };
                var json=JsonConvert.SerializeObject(body);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var http=new HttpClient();
                var resp = await http.PostAsync("http://localhost:5271/api/Account/Login", content);
                var respText=await resp.Content.ReadAsStringAsync();
                if(!resp.IsSuccessStatusCode)
                {
                    ShowAlert($"{resp.StatusCode}", "错误");
                    return;
                }
                var apiResult = JsonConvert.DeserializeObject<APIResult<LoginUserDto>>(respText);
                if(apiResult==null)
                {
                    ShowAlert("失败", "错误");
                    return;
                }

                var data = apiResult.Datas;
                if(apiResult.Code==(int)ResultCode.Success&& data!=null)
                {
                    TokenDto.JwtToken = data.Token ?? string.Empty;
                    TokenDto.Name = userName;
                    TokenDto.Password = pwd;
                    ShowAlert(apiResult.Message, "成功");
                }
                else
                {
                    ShowAlert(apiResult.Message ?? "登录失败", "失败");
                }
            }
            catch (Exception ex)
            {
                ShowAlert($"登录异常: {ex.Message}", "错误");
                throw;
            }
        }
    }
}
